package com.graduation.cdm.funactivity.view.mineview;

import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.graduation.cdm.funactivity.MyApplication;
import com.graduation.cdm.funactivity.R;
import com.graduation.cdm.funactivity.bean.MyEvaluateBean;
import com.graduation.cdm.funactivity.util.CommonAdapter;
import com.graduation.cdm.funactivity.util.GlobalConstant;
import com.graduation.cdm.funactivity.util.ViewHolder;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.graduation.cdm.funactivity.util.DateUtils.longTostring;
import static com.graduation.cdm.funactivity.util.GlobalConstant.preUrl;

public class EvaluateActivity extends AppCompatActivity implements View.OnClickListener {

    private ImageView iv_eva_back;
    private PullToRefreshListView lv_evaluates;

    Integer userId;
    Integer pageNow =1;
    Integer activityId;
    Long evaTime;

    List<MyEvaluateBean.MyEvaluate> myEvaluates = new ArrayList<>();
    CommonAdapter<MyEvaluateBean.MyEvaluate> myEvaluateCommonAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_evaluate);

        initView();
        getData();
    }

    private void  initView(){
        iv_eva_back = ((ImageView) findViewById(R.id.iv_eva_back));
        lv_evaluates = ((PullToRefreshListView) findViewById(R.id.lv_evaluates));

        SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("user_info", Context.MODE_PRIVATE);
        userId = sharedPreferences.getInt("userId",0);

        lv_evaluates.setMode(PullToRefreshBase.Mode.PULL_FROM_END);
        lv_evaluates.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
                AlertDialog.Builder builder = new AlertDialog.Builder(EvaluateActivity.this);
                builder.setMessage("是否要删除此评论？");
                builder.setTitle("提示");
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        activityId = myEvaluates.get(position-1).activityId;
                        evaTime = myEvaluates.get(position-1).evaTime;
                        System.out.println("ssssssss="+myEvaluates.get(position-1));
                        deleteEvaluate();
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builder.create().show();
            }
        });
        lv_evaluates.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                pageNow++;
                getData();
            }
        });

    }

    private void getData(){
        String url = GlobalConstant.preUrl+"evaluate/getMyEvaluate";
        StringRequest evaluateRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                Gson gson = new Gson();
                MyEvaluateBean myEvaluateBean = gson.fromJson(s,MyEvaluateBean.class);
                Integer pageCount = myEvaluateBean.pageSum;
                if (pageNow == 1) {
                    myEvaluates.clear();
                }
                if (pageNow <= pageCount) {
                    myEvaluates.addAll(myEvaluateBean.evaluateList);
                }else {
                    Toast.makeText(getApplicationContext(), "已加载全部数据", Toast.LENGTH_SHORT).show();
                }
                initData();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> map = new HashMap<>();
                map.put("userId",userId+"");
                map.put("pageNow",pageNow+"");
                map.put("pageSize",5+"");
                return map;
            }
        };
        MyApplication.getRequestQueue().add(evaluateRequest);
    }

    private void initData(){
        if (myEvaluateCommonAdapter == null){
            myEvaluateCommonAdapter = new CommonAdapter<MyEvaluateBean.MyEvaluate>(getApplicationContext(),myEvaluates,R.layout.my_evaluate_item) {
                @Override
                public void convert(ViewHolder viewHolder, MyEvaluateBean.MyEvaluate myEvaluate, int position) {
                    TextView tv_createtime = viewHolder.getViewById(R.id.tv_createtime);
                    TextView tv_label = viewHolder.getViewById(R.id.tv_lable);
                    TextView tv_theme = viewHolder.getViewById(R.id.tv_theme);
                    TextView tv_content = viewHolder.getViewById(R.id.tv_content);

                    tv_createtime.setText(longTostring(myEvaluate.evaTime));
                    tv_label.setText(myEvaluate.activityLable);
                    tv_theme.setText(myEvaluate.activityTitle);
                    tv_content.setText(myEvaluate.evaContent);
                }
            };
            lv_evaluates.setAdapter(myEvaluateCommonAdapter);
        }else {
            myEvaluateCommonAdapter.notifyDataSetChanged();
        }
        lv_evaluates.onRefreshComplete();
    }

    private void deleteEvaluate(){
        String url = preUrl+"evaluate/deleteEvaluate";
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                System.out.println("evaluate/deleteEvaluate=="+s.trim());
                try {
                    JSONObject jsonObject = new JSONObject(s);
                    if (jsonObject.get("result").toString().equals("true")){
                        Toast.makeText(getApplicationContext(),"评价已删除！",Toast.LENGTH_SHORT).show();
                        pageNow =1 ;
                        getData();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> map = new HashMap<>();
                map.put("activityId",activityId+"");
                map.put("userId",userId+"");
                map.put("evaTime",longTostring(evaTime));
                return map;
            }
        };
        MyApplication.getRequestQueue().add(stringRequest);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.iv_eva_back:
                finish();
                break;
        }
    }
}
